package com.heima.filter;

import com.heima.wemedia.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.util.Arrays;
import java.util.List;

@Slf4j
@Component
@Order(0)
public class AuthorizeFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        List<String> urlList = Arrays.asList(
                "/v2/api-docs",
                "/login/in"
        );

        //1.获取请求和响应
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //2.过滤需要放行的请求
        String path = request.getURI().getPath();
        for (String url : urlList){
            if (path.endsWith(url)) {
                return chain.filter(exchange);
            }
        }

        //3.判断token是否存在
        String token = request.getHeaders().getFirst("token");
        if (!StringUtils.isBlank(token)) {
            //4.解析token信息
            try {
                Claims claims = AppJwtUtil.getClaimsBody(token);
                int i = AppJwtUtil.verifyToken(claims);
                //4.1若成功 将用户id放在响应头 放行请求到微服务
                if (i < 1) {
                    Object id = claims.get("id");
                    //打印日志
                    log.info("网关获取到userId的值:{}", id);
                    request.mutate().header("userId", String.valueOf(id));
                    return chain.filter(exchange);

                }
            } catch (Exception e) {
                //4.2若解析不成功 添加相应信息并返回
                //打印日志
                e.printStackTrace();
                log.info("网关获取到userId的值:{}", e.getMessage());
            }
        }

        //若不存在 添加相应信息并返回
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();


    }
}